CounterTestbench

Modified

2025-11-11

Source: Lab4/CounterTestbench.sv (modified 2025-11-10 08:18)

// CounterTestbench.sv — TB for single-file CounterDisplay.sv
`timescale 1ns/1ps

module CounterTestbench;

  // DUT ports
  logic        clock;      // KEY0 (active-low button, but在仿真里我们直接做时钟沿)
  logic        clear_n;    // KEY1, sync clear active-low
  logic [3:0]  addBy;      // SW3..SW0
  logic [6:0]  seg0;       // HEX0 (a..g), active-low

  // 可视化的内部“实际计数值”,仅用于显示(从 seg0 反推比较麻烦)
  logic [3:0]  golden_cnt;

  // DUT
  CounterDisplay dut (
    .clock   (clock),
    .clear_n (clear_n),
    .addBy   (addBy),
    .seg0    (seg0)
  );

  // ———— 工具函数:把七段译码的 active-low 再译回 0..F(便于波形观测)————
  function automatic [3:0] seg_to_hex (input logic [6:0] s);
    case (s)
      7'b1000000: seg_to_hex = 4'h0;
      7'b1111001: seg_to_hex = 4'h1;
      7'b0100100: seg_to_hex = 4'h2;
      7'b0110000: seg_to_hex = 4'h3;
      7'b0011001: seg_to_hex = 4'h4;
      7'b0010010: seg_to_hex = 4'h5;
      7'b0000010: seg_to_hex = 4'h6;
      7'b1111000: seg_to_hex = 4'h7;
      7'b0000000: seg_to_hex = 4'h8;
      7'b0010000: seg_to_hex = 4'h9;
      7'b0001000: seg_to_hex = 4'hA;
      7'b0000011: seg_to_hex = 4'hB;
      7'b1000110: seg_to_hex = 4'hC;
      7'b0100001: seg_to_hex = 4'hD;
      7'b0000110: seg_to_hex = 4'hE;
      7'b0001110: seg_to_hex = 4'hF;
      default:     seg_to_hex = 4'hX;
    endcase
  endfunction

  // ———— 任务:模拟“按一次 KEY0”产生上升沿(idle=1, press=0, release=1)————
  task automatic press_clock();
    begin
      clock = 1'b0;   // 先到 0(相当于按下)
      #5;
      clock = 1'b1;   // 释放,产生上升沿(寄存器在posedge采样)
      #5;
    end
  endtask

  // ———— 任务:同步清零(active-low,需要在时钟上升沿生效)————
  task automatic sync_clear();
    begin
      clear_n = 1'b0;  // 低有效
      // 清零是同步的 → 给一个时钟沿
      press_clock();
      clear_n = 1'b1;
      #5;
    end
  endtask

  // ———— 任务:跑 N 步并打印/检查 ————
  task automatic run_steps(input [3:0] step, input int N);
    begin
      addBy = step;
      $display("---- addBy = 0x%0h, run %0d steps ----", step, N);
      repeat (N) begin
        press_clock();
        golden_cnt = (golden_cnt + step) & 4'hF;
        $display("%0t ns : count(hex from seg0) = %0h (golden=%0h)",
                 $time, seg_to_hex(seg0), golden_cnt);
      end
    end
  endtask

  // ———— Stimulus ————
  initial begin
    // 默认空闲电平
    clock    = 1'b1;
    clear_n  = 1'b1;
    addBy    = 4'h0;
    golden_cnt = 4'h0;
    #10;

    // 同步清零
    sync_clear();

    // 按实验给的 5 组:0,1,7,8,F,各做 5 步
    run_steps(4'h0, 5);
    run_steps(4'h1, 5);
    run_steps(4'h7, 5);
    run_steps(4'h8, 5);
    run_steps(4'hF, 5);

    $display("TB finished.");
    #20;
    $finish;
  end

endmodule